package com.nzy.service.impl;

import com.alibaba.fastjson.JSON;
import com.nzy.common.CacheKey;
import com.nzy.common.RedisUtil;
import com.nzy.common.annotate.RecordStock;
import com.nzy.dao.mapper.StockMapper;
import com.nzy.entity.Stock;
import com.nzy.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class StockServiceImpl implements StockService {

    @Autowired
    private StockMapper stockMapper;

    @Autowired
    private RedisUtil redisUtil;


    @RecordStock
    public Integer insert(Stock stock){
        Date date = new Date();
        stock.setCreateTime(date);
        stock.setUpdateTime(date);
        return stockMapper.insert(stock);
    }

    @RecordStock
    public Integer addStock(Stock stock){
        return stockMapper.addStock(stock);
    }
    @RecordStock
    public Integer subStock(Stock stock){
        return stockMapper.subStock(stock);
    }

    public Stock queryBySkuId(String skuId){
        String key = CacheKey.getStockBySkuId(skuId);
        Stock stock = redisUtil.getBean(key, Stock.class);
        if(stock == null){
            stock = stockMapper.selectBySkuId(skuId);
            redisUtil.set(key, JSON.toJSONString(stock));
        }
        return stock;
    }

    public Integer queryNumBySkuId(String skuId){
        String key = CacheKey.getStockNumBySkuId(skuId);
        Integer number = (Integer)redisUtil.get(key);
        if(number == null){
            Stock stock = stockMapper.selectBySkuId(skuId);
            number = stock.getStock();
            redisUtil.set(key, number);
        }
        return number;
    }

}
